package com.example;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.field.RtfPageNumber;
import com.lowagie.text.rtf.field.RtfTotalPageNumber;
import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter;

import java.awt.*;
import java.io.FileOutputStream;
import java.util.Iterator;

/**
 * 只能自己管理高度了
 * 自己管理高度，自己判断分页
 */
public class MyPrinter {

    /**
     * 需要输出的文件名字
     */
    private String mFileName;

    /**
     * 换行的段落，就是一个段落，里面的文本是\n
     */
    private Paragraph mLineFeed;

    /**
     * 统一的字体对象
     */
    private Font mFont;

    private static final int FONT_SIZE_TITLE = 18;//标题的字体大小

    private static final int FONT_SIZE_TABLE_HEAD = 11;//表头的字体大小

    private static final int FONT_SIZE_TABLE_CONTENT = 10;//表的内容的字体大小


    public MyPrinter(String fileName){
        mFileName = fileName;
        mLineFeed = new Paragraph("\n");
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont("font/Deng.ttf",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//等线体，基本上操作系统都有该字体
        } catch (Exception e) {
            e.printStackTrace();
        }
        mFont = new Font(bfChinese, 10, Font.NORMAL);//不加粗，字号10
    }

    /**
     * 打印输出
     */
    public void print(){
        printWord();
        //printPDF();
    }

    /**
     * 打印输出word
     */
    public void printWord(){
        Document document = new Document(PageSize.A4);
        try {
            RtfWriter2.getInstance(document, new FileOutputStream(mFileName));
            document.open();//打开
            //打印汇总表
            printSummaryTable(document);
            document.newPage();//跳转到下一页

            //打印详测表
            printDetailedTestTable(document);
            document.newPage();//跳转到下一页

            //打印原始记录表
            printOriginalRecordTable(document);
            document.newPage();//跳转到下一页

            //打印图
            printGraph(document);

            //设置页眉和页脚
            setHeadAndFoot(document);
            document.close();//关闭
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printPDF(){
        /*MyDocument document = new MyDocument(PageSize.A4);
        try {
            PdfWriter.getInstance(document, new FileOutputStream("outputDoc/003.pdf"));
            document.open();//打开
            //打印汇总表
            printSummaryTable(document);
            document.close();//关闭
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 打印汇总表
     */
    private void printSummaryTable(Document document) throws DocumentException {
        //添加汇总表的标题
        addTableTitle(document, "单桩竖向抗压静载试验汇总表");

        //添加工程的基本信息
        addProjectPrimaryInfo(document);

        //添加表格
        Table table = new Table(6);//6列
        table.setBorderWidth(1);
        table.setBorderColor(new Color(0, 0, 0));
        table.setPadding(5);
        //table.setSpacing(5);

        //添加表头
        addSummaryTableHead(table);

        //添加表体
        mFont.setSize(FONT_SIZE_TABLE_CONTENT);
        for(int i = 0; i < 15; i++){
            table.addCell(new Cell(new Chunk("" + i, mFont)));
            table.addCell(new Cell(new Chunk("" + i, mFont)));
            table.addCell(new Cell(new Chunk("" + i, mFont)));
            table.addCell(new Cell(new Chunk("" + i, mFont)));
            table.addCell(new Cell(new Chunk("" + i, mFont)));
            table.addCell(new Cell(new Chunk("" + i, mFont)));
        }
        //添加最后一行的单元格
        Cell cell = new Cell();
        cell.setColspan(6);
        cell.add(new Chunk("最大沉降量:   7.18 mm          最大回弹量:   1.16 mm         回弹率: 16.16%", mFont));
        table.addCell(cell);
        table.setWidth(100);//百分比，最大是100
        setTableCellCenter(table);//让表格的所有单元格居中
        document.add(table);

    }

    /**
     * 打印详测表
     */
    private void printDetailedTestTable(Document document) throws DocumentException {
        //打印标题
        addTableTitle(document, "单桩竖向抗压静载试验详测表");

        //打印工程基本信息
        addProjectPrimaryInfo(document);

        //打印表格
        Table table = new Table(9);
        table.setBorderWidth(1);
        table.setBorderColor(new Color(0, 0, 0));
        table.setPadding(5);
        //打印表头
        addDetailTestTableHead(table);

        //打印表格的内容
        mFont.setSize(FONT_SIZE_TABLE_CONTENT);
        //总共20级
        for(int i = 0; i < 20; i++){
            Cell grade = new Cell();
            grade.setRowspan(6);
            grade.add(new Chunk("" + i, mFont));
            table.addCell(grade);
            for(int j = 0; j < 6; j++){
                for(int k = 0; k < 8; k++){
                    Cell cell = new Cell(new Chunk("" + k, mFont));
                    table.addCell(cell);
                }
            }
        }

        //向文档中添加表格
        setTableCellCenter(table);//让表格的所有项都居中
        table.setWidth(100);
        document.add(table);
    }

    /**
     * 打印原始记录表
     */
    private void printOriginalRecordTable(Document document) throws DocumentException {
        //打印标题
        addTableTitle(document, "单桩竖向抗压静载试验原始记录表");
        //打印原始记录表中的基本信息表
        addOriginalProjectInfoTable(document);

        //打印测试记录表格
        Table tableTestRecord = new Table(12);
        tableTestRecord.setBorderWidth(1);
        tableTestRecord.setBorderColor(new Color(0, 0, 0));
        tableTestRecord.setPadding(5);
        //打印表头
        addOriginalTestRecordTableHead(tableTestRecord);

        //打印表格的内容
        mFont.setSize(FONT_SIZE_TABLE_CONTENT);
        for(int i = 0; i < 20; i++){
            Cell grade = new Cell(new Chunk("" + i, mFont));
            grade.setRowspan(6);
            tableTestRecord.addCell(grade);
            for(int j = 0; j < 6; j++){
                for(int k = 0; k < 11; k++){
                    Cell cell = new Cell(new Chunk("" + k, mFont));
                    tableTestRecord.addCell(cell);
                }
            }
        }

        setTableCellCenter(tableTestRecord);
        tableTestRecord.setWidth(100);
        document.add(tableTestRecord);

    }

    /**
     * 打印图
     */
    private void printGraph(Document document) throws DocumentException {
        Table table = new Table(11);
        table.setBorderWidth(1);
        table.setBorderColor(new Color(0, 0, 0));
        table.setPadding(5);
        mFont.setSize(FONT_SIZE_TABLE_CONTENT);
        Cell projectName = new Cell(new Chunk("工程名称： aaaaaaaa", mFont));
        projectName.setColspan(7);
        Cell pipeNum = new Cell(new Chunk("试验桩号： d2-16", mFont));
        pipeNum.setColspan(4);
        Cell date = new Cell(new Chunk("测试日期： 2017-09-24", mFont));
        date.setColspan(3);
        Cell pipeLen = new Cell(new Chunk("桩长：", mFont));
        pipeLen.setColspan(4);
        Cell pipeDiameter = new Cell(new Chunk("桩径：", mFont));
        pipeDiameter.setColspan(4);
        Cell load = new Cell(new Chunk("荷载(kN)", mFont));
        Cell ld1 = new Cell(new Chunk("1", mFont));
        Cell ld2 = new Cell(new Chunk("2", mFont));
        Cell ld3 = new Cell(new Chunk("3", mFont));
        Cell ld4 = new Cell(new Chunk("4", mFont));
        Cell ld5 = new Cell(new Chunk("5", mFont));
        Cell ld6 = new Cell(new Chunk("6", mFont));
        Cell ld7 = new Cell(new Chunk("7", mFont));
        Cell ld8 = new Cell(new Chunk("8", mFont));
        Cell ld9 = new Cell(new Chunk("9", mFont));
        Cell ld10 = new Cell(new Chunk("10", mFont));
        Cell settle = new Cell(new Chunk("沉降(mm)", mFont));
        Cell st1 = new Cell(new Chunk("1", mFont));
        Cell st2 = new Cell(new Chunk("2", mFont));
        Cell st3 = new Cell(new Chunk("3", mFont));
        Cell st4 = new Cell(new Chunk("4", mFont));
        Cell st5 = new Cell(new Chunk("5", mFont));
        Cell st6 = new Cell(new Chunk("6", mFont));
        Cell st7 = new Cell(new Chunk("7", mFont));
        Cell st8 = new Cell(new Chunk("8", mFont));
        Cell st9 = new Cell(new Chunk("9", mFont));
        Cell st10 = new Cell(new Chunk("10", mFont));
        table.addCell(projectName);
        table.addCell(pipeNum);
        table.addCell(date);
        table.addCell(pipeLen);
        table.addCell(pipeDiameter);
        table.addCell(load);
        table.addCell(ld1);
        table.addCell(ld2);
        table.addCell(ld3);
        table.addCell(ld4);
        table.addCell(ld5);
        table.addCell(ld6);
        table.addCell(ld7);
        table.addCell(ld8);
        table.addCell(ld9);
        table.addCell(ld10);
        table.addCell(settle);
        table.addCell(st1);
        table.addCell(st2);
        table.addCell(st3);
        table.addCell(st4);
        table.addCell(st5);
        table.addCell(st6);
        table.addCell(st7);
        table.addCell(st8);
        table.addCell(st9);
        table.addCell(st10);
        Iterator it = table.iterator();
        it.next();
        it.next();
        Row row3 = (Row) it.next();
        Row row4 = (Row) it.next();
        setToCenterInRow(row3);
        setToCenterInRow(row4);
        table.setWidth(100);
        document.add(table);
    }

    /**
     * 将某一行的但永远个居中对齐
     */
    private void setToCenterInRow(Row row){
        for(int i = 0; i < row.getColumns(); i++){
            Cell cell = (Cell) row.getCell(i);
            if(cell != null){
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
            }
        }
    }

    /**
     * 设置页眉和页脚
     */
    private void setHeadAndFoot(Document document){
        //设置页眉
        /*HeaderFooter header = new HeaderFooter(new Phrase("页眉的测试", mFont),false);
        header.setAlignment(HeaderFooter.ALIGN_CENTER);
        document.setHeader(header);*/

        // 设置页脚
        RtfPageNumber number = new RtfPageNumber();
        Paragraph parafooter = new Paragraph();
        parafooter.add(new Phrase("第", mFont));
        parafooter.add(number);
        parafooter.add(new Phrase("页/共", mFont));
        parafooter.add(new RtfTotalPageNumber());
        parafooter.add(new Phrase("页", mFont));
        HeaderFooter footer = new RtfHeaderFooter(parafooter);
        footer.setAlignment(Element.ALIGN_CENTER);
        footer.setBorder(Rectangle.NO_BORDER);
        document.setFooter(footer);
        // 设置页脚完毕
    }

    /**
     * 为表格添加标题，标题不是表头
     * @param title 需要添加的标题
     */
    private void addTableTitle(Document document, String title) throws DocumentException {
        mFont.setStyle(Font.BOLD);//加粗
        mFont.setSize(FONT_SIZE_TITLE);//大小是18号
        Paragraph titleHuiZong = new Paragraph(title, mFont);
        titleHuiZong.setAlignment(Element.ALIGN_CENTER);
        document.add(titleHuiZong);
        //document.add(mLineFeed);//添加换行
    }

    /**
     * 添加工程的基本的信息
     * 每一张表的最前面都是这些信息
     */
    private void addProjectPrimaryInfo(Document document) throws DocumentException {
        //添加工地名称，试验桩号
        mFont.setSize(FONT_SIZE_TABLE_HEAD);
        mFont.setStyle(Font.NORMAL);
        Chunk projectName = new Chunk("工地名称：aaaaaaa", mFont);
        Chunk pipeNum = new Chunk("试验桩号：1302", mFont);
        Chunk fillChunk = new Chunk(generateEmptyString(130), mFont);
        fillChunk.setTextRise(80);
        Paragraph pp1 = new Paragraph();
        //pp1.setSpacingAfter(50);//设置该段落前面要空多少高度
        //pp1.setSpacingBefore(50);//设置该段落后面要空多少高度
        pp1.add(projectName);
        pp1.add(fillChunk);
        pp1.add(pipeNum);
        document.add(pp1);

        //添加测试日期，桩长，桩径
        Paragraph pp2 = new Paragraph();
        Chunk date = new Chunk("测试日期：2018-01-02", mFont);
        Chunk pipeLen = new Chunk("桩长：10m", mFont);
        Chunk pipeDiameter = new Chunk("桩径：3m", mFont);
        pp2.add(date);
        pp2.add(new Chunk(generateEmptyString(25), mFont));
        pp2.add(pipeLen);
        pp2.add(new Chunk(generateEmptyString(27), mFont));
        pp2.add(pipeDiameter);
        document.add(pp2);
    }

    /**
     * 添加汇总表格的表头
     */
    private void addSummaryTableHead(Table table) throws BadElementException {
        Font font = getTableHeadFont();
        Cell serialNum = new Cell(new Chunk("序号", font));
        serialNum.setRowspan(2);
        Cell load = new Cell(new Chunk("荷载\n(KN)", font));
        load.setRowspan(2);
        Cell time = new Cell(new Chunk("历 时(min)", font));
        time.setColspan(2);
        Cell settle = new Cell(new Chunk("沉降10(mm)", font));
        settle.setColspan(2);
        Cell timeThisLevel = new Cell(new Chunk("本级", font));
        Cell timeSum = new Cell(new Chunk("累计", font));
        Cell settleThisLevel = new Cell(new Chunk("本级", font));
        Cell settleSum = new Cell(new Chunk("累计", font));
        table.addCell(serialNum);
        table.addCell(load);
        table.addCell(time);
        table.addCell(settle);
        table.addCell(timeThisLevel);
        table.addCell(timeSum);
        table.addCell(settleThisLevel);
        table.addCell(settleSum);
        table.endHeaders();//能保持表头,非常关键，分页之后,每页都会有表头
    }

    /**
     * 添加详测表的表头
     */
    private void addDetailTestTableHead(Table table){
        Font font = getTableHeadFont();
        Cell load = new Cell();
        load.setRowspan(2);
        load.add(new Chunk("荷载\n(KN)", font));
        Cell time = new Cell();
        time.setColspan(2);
        time.add(new Chunk("观测时间(min)", font));
        Cell value = new Cell();
        value.setColspan(2);
        value.add(new Chunk("读 数 (mm)", font));
        Cell settlement = new Cell();
        settlement.setColspan(4);
        settlement.add(new Chunk("平均沉降(mm)", font));
        Cell timeThisLevel = new Cell();
        timeThisLevel.add(new Chunk("本 级", font));
        Cell timeSum = new Cell();
        timeSum.add(new Chunk("累 计", font));
        Cell t1 = new Cell();
        t1.add(new Chunk("表 1", font));
        Cell t2 = new Cell();
        t2.add(new Chunk("表 2", font));
        Cell t3 = new Cell();
        t3.add(new Chunk("表 3", font));
        Cell t4 = new Cell();
        t4.add(new Chunk("表 4", font));
        Cell settleThisLevel = new Cell();
        settleThisLevel.add(new Chunk("本 级", font));
        Cell settleSum = new Cell();
        settleSum.add(new Chunk("累 计", font));
        table.addCell(load);
        table.addCell(time);
        table.addCell(value);
        table.addCell(settlement);
        table.addCell(timeThisLevel);
        table.addCell(timeSum);
        table.addCell(t1);
        table.addCell(t2);
        table.addCell(t3);
        table.addCell(t4);
        table.addCell(settleThisLevel);
        table.addCell(settleSum);
        table.endHeaders();//这个设置很重要，表格超过一页的时候，每一页上面都会有表格
    }

    /**
     * 打印原始记录表里面的工程基本信息的表格
     */
    private void addOriginalProjectInfoTable(Document document) throws DocumentException {
        //打印工程基本信息
        Table tableProjectInfo = new Table(6);
        tableProjectInfo.setBorderWidth(1);
        tableProjectInfo.setPadding(5);
        tableProjectInfo.setBorderColor(new Color(0, 0, 0));
        mFont.setSize(FONT_SIZE_TABLE_CONTENT);
        mFont.setStyle(Font.NORMAL);
        Cell projectName = new Cell(new Chunk("工程名称：aaaaaaaa", mFont));
        projectName.setColspan(4);
        Cell pipeNum = new Cell(new Chunk("试验桩号：d2-16", mFont));
        pipeNum.setColspan(2);
        Cell testTime = new Cell(new Chunk("测试时间：2017-09-24  21:11", mFont));
        testTime.setColspan(2);
        Cell pipeLen = new Cell(new Chunk("桩长：  0.0m", mFont));
        pipeLen.setColspan(2);
        Cell pipeDiameter = new Cell(new Chunk("桩径：0 mm", mFont));
        pipeDiameter.setColspan(2);
        Cell gps = new Cell(new Chunk("GPS坐标信息：经度=116.572083, 纬度=35.393826", mFont));
        gps.setColspan(3);
        Cell instrumentNum = new Cell(new Chunk("测试仪器编号", mFont));
        instrumentNum.setColspan(3);
        Cell testMethod = new Cell(new Chunk("试验方法：快速维持荷载法——1小时", mFont));
        testMethod.setColspan(3);
        Cell maxPredictedLoad = new Cell(new Chunk("最大预估载荷：4000 kN", mFont));
        maxPredictedLoad.setColspan(3);
        Cell jackNumber = new Cell(new Chunk("千斤顶编号：091227", mFont));
        jackNumber.setColspan(2);
        Cell jackCount = new Cell(new Chunk("千斤顶数量：1", mFont));
        jackCount.setColspan(2);
        Cell jackDiameter = new Cell(new Chunk("千斤顶内径：300 mm", mFont));
        jackDiameter.setColspan(2);
        Cell displacementTCH = new Cell(new Chunk("位移测试通道：s1   s2   s3   s4   ", mFont));
        displacementTCH.setColspan(3);
        Cell anchor = new Cell(new Chunk("锚桩位移监测通道：无", mFont));
        anchor.setColspan(3);
        Cell displacementSensorNumber = new Cell(new Chunk("位移传感器编号：2003001    2003002    2003003    2003004    ", mFont));
        displacementSensorNumber.setColspan(6);
        Cell pressureSensorType = new Cell(new Chunk("压力传感器类型：油压", mFont));
        pressureSensorType.setColspan(3);
        Cell pressureSensorNum = new Cell(new Chunk("压力传感器编号：", mFont));
        pressureSensorNum.setColspan(3);
        Cell loadingInterval = new Cell(new Chunk("加载读数间隔：0    5    10    15    15    15    30    30    ...  分", mFont));
        loadingInterval.setColspan(6);
        Cell unLoadingInterval = new Cell(new Chunk("卸载读数间隔：0    15    15    30    30    30    ...  分", mFont));
        unLoadingInterval.setColspan(6);

        tableProjectInfo.addCell(projectName);
        tableProjectInfo.addCell(pipeNum);
        tableProjectInfo.addCell(testTime);
        tableProjectInfo.addCell(pipeLen);
        tableProjectInfo.addCell(pipeDiameter);
        tableProjectInfo.addCell(gps);
        tableProjectInfo.addCell(instrumentNum);
        tableProjectInfo.addCell(testMethod);
        tableProjectInfo.addCell(maxPredictedLoad);
        tableProjectInfo.addCell(jackNumber);
        tableProjectInfo.addCell(jackCount);
        tableProjectInfo.addCell(jackDiameter);
        tableProjectInfo.addCell(displacementTCH);
        tableProjectInfo.addCell(anchor);
        tableProjectInfo.addCell(displacementSensorNumber);
        tableProjectInfo.addCell(pressureSensorType);
        tableProjectInfo.addCell(pressureSensorNum);
        tableProjectInfo.addCell(loadingInterval);
        tableProjectInfo.addCell(unLoadingInterval);
        tableProjectInfo.setWidth(100);
        document.add(tableProjectInfo);
    }

    /**
     * 打印原始记录表之测试记录表的表头
     */
    private void addOriginalTestRecordTableHead(Table tableTestRecord) throws BadElementException {
        Font font = getTableHeadFont();
        Cell thisLevelLoad = new Cell(new Chunk("本级\n" + "荷载\n" + "(kN)\n", font));
        thisLevelLoad.setRowspan(2);
        Cell realLoad = new Cell(new Chunk("实测\n" + "荷载\n" +"(kN)\n", font));
        realLoad.setRowspan(2);
        Cell realPressure = new Cell(new Chunk("实测\n" + "油压\n" + "(MPa)\n", font));
        realPressure.setRowspan(2);
        Cell time = new Cell(new Chunk("记录\n" + "时间\n" + "时:分\n", font));
        time.setRowspan(2);
        Cell realSpace = new Cell(new Chunk("实际\n" + "间隔\n" + "(min)\n", font));
        realSpace.setRowspan(2);
        Cell realValue = new Cell(new Chunk("实 测 读 数 (mm)", font));
        realValue.setColspan(4);
        Cell thisLevelSettle = new Cell(new Chunk("本级\n" + "沉降\n" + "(mm)\n", font));
        thisLevelSettle.setRowspan(2);
        Cell average = new Cell(new Chunk("平均\n" + "沉降\n" + "(mm)\n", font));
        average.setRowspan(2);
        Cell remarks = new Cell(new Chunk("备注", font));
        remarks.setRowspan(2);
        Cell t1 = new Cell(new Chunk("表\n1", font));
        Cell t2 = new Cell(new Chunk("表\n2", font));
        Cell t3 = new Cell(new Chunk("表\n3", font));
        Cell t4 = new Cell(new Chunk("表\n4", font));
        tableTestRecord.addCell(thisLevelLoad);
        tableTestRecord.addCell(realLoad);
        tableTestRecord.addCell(realPressure);
        tableTestRecord.addCell(time);
        tableTestRecord.addCell(realSpace);
        tableTestRecord.addCell(realValue);
        tableTestRecord.addCell(thisLevelSettle);
        tableTestRecord.addCell(average);
        tableTestRecord.addCell(remarks);
        tableTestRecord.addCell(t1);
        tableTestRecord.addCell(t2);
        tableTestRecord.addCell(t3);
        tableTestRecord.addCell(t4);
        tableTestRecord.endHeaders();//当表格需要多页时，每页上面都会有表头
    }

    /**
     * 获取表头的字体
     */
    private Font getTableHeadFont(){
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont("font/Deng.ttf",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//等线体，基本上操作系统都有该字体
        } catch (Exception e) {
            e.printStackTrace();
        }
        Font font = new Font(bfChinese, FONT_SIZE_TABLE_HEAD, Font.NORMAL);
        return font;
    }

    /**
     * 让表格的单元格居中
     */
    private void setTableCellCenter(Table table){
        Iterator it = table.iterator();
        while(it.hasNext()){
            Row row = (Row) it.next();
            int columnCount = row.getColumns();
            //MyLog.log("columnCount = " + columnCount);
            for(int i = 0; i < columnCount; i++){
                Cell cell = (Cell) row.getCell(i);
                if(cell != null){
                    cell.setVerticalAlignment(Element.ALIGN_CENTER);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                }
            }
        }
    }

    /**
     * 生成空的string
     * @param len 需要生成的空string的长度
     */
    private String generateEmptyString(int len){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < len; i++){
            sb.append(" ");
        }
        return sb.toString();
    }



}
